<template>
  <div class="image-preview-container">
    <div
      v-for="(item, index) in imgs"
      :key="index"
      class="image-item"
      @click="showPreview(field ? item[field] : item)"
    >
      <img :src="field ? item[field] : item" class="preview-img" alt="" />
    </div>

    <div
      v-if="isPreviewVisible"
      class="preview-modal"
      @click.self="closePreview"
    >
      <img :src="currentPreviewUrl" alt="Preview" class="modal-img" />
      <button @click="closePreview" class="close-btn">×</button>
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from "vue"

// 存储图片列表，外部传入
const props = defineProps({
  imageList: {
    type: Array,
    required: true
  },
  // 图片列表的字段, 不传直接取当前item
  field: {
    type: String,
    required: false
  },
  // 当前图片列表前几项，不传取全部
  length: {
    type: Number,
    required: false
  }
})

const imgs = computed(() =>
  props.length ? props.imageList.slice(0, props.length) : props.imageList
)
// 是否显示预览模态框
const isPreviewVisible = ref(false)
// 当前正在预览的图片地址
const currentPreviewUrl = ref("")

// 显示图片预览
const showPreview = url => {
  currentPreviewUrl.value = url
  isPreviewVisible.value = true
}

// 关闭图片预览
const closePreview = () => {
  isPreviewVisible.value = false
}
</script>

<style scoped>
.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-item {
  cursor: pointer;
}

.preview-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.modal-img {
  max-width: 80%;
  max-height: 80%;
}

.close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: transparent;
  color: white;
  border: none;
  font-size: 36px;
  cursor: pointer;
}
</style>
